﻿using System;
using System.Data.SqlClient;
using System.Linq;
using System.Net.Http;
using System.Threading;
using Common.Logging;
using Newtonsoft.Json;
using OutDbContext;
using Rmq.Center;
using User.Api.HttpClients;
using In.Api.Dto.HisWs;

namespace Out.TaskRunner.RmqWorkers
{
    public class OrderUnapptingWorker : IWorker
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(OrderUnapptingWorker));

        public void Start(CancellationToken ct)
        {
            if (ct.IsCancellationRequested)
            {
                return;
            }

            using (var consumer = new OrderUnapptingConsumer())
            {
                consumer.Subscribe((id, count, dt, msg, channel) =>
                {
                    if (msg.OrderType == OrderType.挂号订单)
                    {
                        return ProcessRegOrder(msg.OrderId, msg.Reason, channel);
                    }

                    return new ConsumedResult { Ack = true };
                });

                while (true)
                {
                    if (ct.IsCancellationRequested)
                    {
                        break;
                    }

                    Thread.Sleep(500);
                }
            }
        }

        private ConsumedResult ProcessRegOrder(int orderId, int reason, WrapperChannel channel)
        {
            string orderNo;
            using (var ctx = new HzfyWeiXinEntities())
            {
                var order = ctx.ApptOrder.Where(x => x.Id == orderId)
                    .Select(x => new
                    {
                        x.OrderNo
                    }).FirstOrDefault();
                if (order == null)
                {
                    return new ConsumedResult
                    {
                        Ack = true
                    };
                }
                orderNo = order.OrderNo;
            }

            var unApptRequest = new Request4CancelAppoint();
            unApptRequest.OrderId = orderNo;
            Response4CancelAppoint unApptResponse;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisNewWs/CancelAppoint", unApptRequest).Result;
                responseMsg.EnsureSuccessStatusCode();
                unApptResponse = responseMsg.Content.ReadAsAsync<Response4CancelAppoint>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内取消预约Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                return new ConsumedResult
                {
                    Ack = true
                };
            }
            finally
            {
                // RMQ 取消锁号
                var unlockingProducer = new OrderUnlockingProducer();
                unlockingProducer.Publish(new OrderUnlockingMsg
                {
                    OrderType = OrderType.挂号订单,
                    OrderId = orderId
                });
            }

            if (unApptResponse.ResultCode == "0")
            {
                if (reason == 1)
                {
                    using (var ctx = new HzfyWeiXinEntities())
                    {
                        var para = new SqlParameter[]
                        {
                            new SqlParameter("@CancelByUserTime", DateTime.Now),
                            new SqlParameter("@OrderId", orderId)
                        };
                        ctx.Database.ExecuteSqlCommand(
                            "Update ApptOrder set CancelByUserTime= @CancelByUserTime where Id=@OrderId", para);
                    }
                }
                if (reason == 2)
                {
                    using (var ctx = new HzfyWeiXinEntities())
                    {
                        var para = new SqlParameter[]
                        {
                            new SqlParameter("@CancelBySysTime", DateTime.Now),
                            new SqlParameter("@OrderId", orderId)
                        };
                        ctx.Database.ExecuteSqlCommand(
                            "Update ApptOrder set CancelBySysTime= @CancelBySysTime where Id=@OrderId", para);
                    }
                }
                if (reason == 3)
                {
                    using (var ctx = new HzfyWeiXinEntities())
                    {
                        var para = new SqlParameter[]
                        {
                            new SqlParameter("@CancelByHospTime", DateTime.Now),
                            new SqlParameter("@OrderId", orderId)
                        };
                        ctx.Database.ExecuteSqlCommand(
                            "Update ApptOrder set CancelByHospTime= @CancelByHospTime where Id=@OrderId", para);
                    }
                }

            }

            return new ConsumedResult
            {
                Ack = true
            };
        }



    }
}